<?php
session_start();

// 检查登录状态
if (!isset($_SESSION['admin_id'])) {
    header('Location: ../login.html');
    exit;
}

// 数据库配置
$db_config = [
    'host' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'fastadmin'
];

// 连接数据库
function connectDB($config) {
    try {
        $pdo = new PDO(
            "mysql:host={$config['host']};dbname={$config['database']};charset=utf8mb4",
            $config['username'],
            $config['password'],
            [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false
            ]
        );
        return $pdo;
    } catch (PDOException $e) {
        die("数据库连接失败: " . $e->getMessage());
    }
}

// 获取统计数据
function getStatistics() {
    global $db_config;
    
    try {
        $pdo = connectDB($db_config);
        
        $stats = [];
        
        // 用户总数
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM fa_user WHERE status = 'normal'");
        $stats['user_count'] = $stmt->fetch()['count'];
        
        // 今日新增用户
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM fa_user WHERE status = 'normal' AND DATE(FROM_UNIXTIME(createtime)) = CURDATE()");
        $stats['today_users'] = $stmt->fetch()['count'];
        
        // 订单总数
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM fa_order WHERE status != 'cancelled'");
        $stats['order_count'] = $stmt->fetch()['count'];
        
        // 今日订单
        $stmt = $pdo->query("SELECT COUNT(*) as count FROM fa_order WHERE status != 'cancelled' AND DATE(FROM_UNIXTIME(createtime)) = CURDATE()");
        $stats['today_orders'] = $stmt->fetch()['count'];
        
        // 总收入
        $stmt = $pdo->query("SELECT COALESCE(SUM(total_amount), 0) as total FROM fa_order WHERE status = 'paid'");
        $stats['total_revenue'] = $stmt->fetch()['total'];
        
        // 今日收入
        $stmt = $pdo->query("SELECT COALESCE(SUM(total_amount), 0) as total FROM fa_order WHERE status = 'paid' AND DATE(FROM_UNIXTIME(createtime)) = CURDATE()");
        $stats['today_revenue'] = $stmt->fetch()['total'];
        
        return $stats;
    } catch (PDOException $e) {
        error_log("获取统计数据失败: " . $e->getMessage());
        return [
            'user_count' => 0,
            'today_users' => 0,
            'order_count' => 0,
            'today_orders' => 0,
            'total_revenue' => 0,
            'today_revenue' => 0
        ];
    }
}

// 获取最近登录记录
function getRecentLogins() {
    global $db_config;
    
    try {
        $pdo = connectDB($db_config);
        $stmt = $pdo->prepare("
            SELECT username, ip, createtime 
            FROM fa_admin_log 
            WHERE title = '管理员登录' 
            ORDER BY createtime DESC 
            LIMIT 10
        ");
        $stmt->execute();
        return $stmt->fetchAll();
    } catch (PDOException $e) {
        error_log("获取登录记录失败: " . $e->getMessage());
        return [];
    }
}

// 处理退出登录
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ../login.html');
    exit;
}

$stats = getStatistics();
$recent_logins = getRecentLogins();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统 - 首页</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f6fa;
            color: #333;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-size: 24px;
            font-weight: 600;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        .user-info span {
            font-size: 14px;
        }
        
        .logout-btn {
            background: rgba(255,255,255,0.2);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            transition: background 0.3s ease;
        }
        
        .logout-btn:hover {
            background: rgba(255,255,255,0.3);
        }
        
        .container {
            display: flex;
            min-height: calc(100vh - 70px);
        }
        
        .sidebar {
            width: 250px;
            background: white;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            padding: 20px 0;
        }
        
        .menu-item {
            padding: 15px 25px;
            cursor: pointer;
            transition: background 0.3s ease;
            border-left: 3px solid transparent;
        }
        
        .menu-item:hover {
            background: #f8f9fa;
            border-left-color: #667eea;
        }
        
        .menu-item.active {
            background: #f8f9fa;
            border-left-color: #667eea;
            color: #667eea;
        }
        
        .menu-item i {
            margin-right: 10px;
            width: 20px;
        }
        
        .main-content {
            flex: 1;
            padding: 30px;
        }
        
        .welcome-section {
            background: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        
        .welcome-section h2 {
            color: #333;
            margin-bottom: 10px;
        }
        
        .welcome-section p {
            color: #666;
            line-height: 1.6;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            text-align: center;
        }
        
        .stat-card h3 {
            color: #666;
            font-size: 14px;
            margin-bottom: 10px;
            text-transform: uppercase;
        }
        
        .stat-card .number {
            font-size: 32px;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }
        
        .stat-card .change {
            font-size: 12px;
            color: #28a745;
        }
        
        .recent-activity {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        
        .recent-activity h3 {
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }
        
        .activity-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 15px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .activity-item:last-child {
            border-bottom: none;
        }
        
        .activity-info {
            flex: 1;
        }
        
        .activity-user {
            font-weight: 600;
            color: #333;
        }
        
        .activity-detail {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }
        
        .activity-time {
            font-size: 12px;
            color: #999;
        }
        
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>后台管理系统</h1>
        <div class="user-info">
            <span>欢迎，<?php echo htmlspecialchars($_SESSION['admin_username']); ?></span>
            <span>登录时间：<?php echo date('Y-m-d H:i:s', $_SESSION['admin_login_time']); ?></span>
            <a href="?logout=1" class="logout-btn">退出登录</a>
        </div>
    </div>
    
    <div class="container">
        <div class="sidebar">
            <div class="menu-item active">
                <i>🏠</i> 首页
            </div>
            <div class="menu-item">
                <i>👥</i> 用户管理
            </div>
            <div class="menu-item">
                <i>📦</i> 订单管理
            </div>
            <div class="menu-item">
                <i>🏪</i> 商品管理
            </div>
            <div class="menu-item">
                <i>📊</i> 数据统计
            </div>
            <div class="menu-item">
                <i>⚙️</i> 系统设置
            </div>
            <div class="menu-item">
                <i>📝</i> 日志管理
            </div>
        </div>
        
        <div class="main-content">
            <div class="welcome-section">
                <h2>欢迎回来，<?php echo htmlspecialchars($_SESSION['admin_username']); ?>！</h2>
                <p>今天是 <?php echo date('Y年m月d日'); ?>，祝您工作愉快！</p>
            </div>
            
            <div class="stats-grid">
                <div class="stat-card">
                    <h3>用户总数</h3>
                    <div class="number"><?php echo number_format($stats['user_count']); ?></div>
                    <div class="change">今日新增: +<?php echo $stats['today_users']; ?></div>
                </div>
                
                <div class="stat-card">
                    <h3>订单总数</h3>
                    <div class="number"><?php echo number_format($stats['order_count']); ?></div>
                    <div class="change">今日新增: +<?php echo $stats['today_orders']; ?></div>
                </div>
                
                <div class="stat-card">
                    <h3>总收入</h3>
                    <div class="number">¥<?php echo number_format($stats['total_revenue'], 2); ?></div>
                    <div class="change">今日收入: ¥<?php echo number_format($stats['today_revenue'], 2); ?></div>
                </div>
                
                <div class="stat-card">
                    <h3>系统状态</h3>
                    <div class="number">正常</div>
                    <div class="change">运行时间: <?php echo round((time() - $_SESSION['admin_login_time']) / 3600, 1); ?>小时</div>
                </div>
            </div>
            
            <div class="recent-activity">
                <h3>最近登录记录</h3>
                <?php if (empty($recent_logins)): ?>
                    <p style="color: #999; text-align: center; padding: 20px;">暂无登录记录</p>
                <?php else: ?>
                    <?php foreach ($recent_logins as $login): ?>
                        <div class="activity-item">
                            <div class="activity-info">
                                <div class="activity-user"><?php echo htmlspecialchars($login['username']); ?></div>
                                <div class="activity-detail">IP地址: <?php echo htmlspecialchars($login['ip']); ?></div>
                            </div>
                            <div class="activity-time">
                                <?php echo date('Y-m-d H:i:s', $login['createtime']); ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <script>
        // 菜单项点击事件
        document.querySelectorAll('.menu-item').forEach(item => {
            item.addEventListener('click', function() {
                // 移除所有active类
                document.querySelectorAll('.menu-item').forEach(i => i.classList.remove('active'));
                // 添加active类到当前项
                this.classList.add('active');
                
                // 这里可以添加页面切换逻辑
                const menuText = this.textContent.trim();
                console.log('点击菜单:', menuText);
            });
        });
        
        // 自动刷新页面（每5分钟）
        setInterval(() => {
            // 可以在这里添加AJAX请求来更新数据
            console.log('页面数据自动刷新');
        }, 5 * 60 * 1000);
        
        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('后台管理系统加载完成');
            
            // 检查会话状态
            const loginTime = <?php echo $_SESSION['admin_login_time']; ?>;
            const currentTime = Math.floor(Date.now() / 1000);
            const sessionDuration = currentTime - loginTime;
            
            // 如果会话超过8小时，提示用户
            if (sessionDuration > 8 * 3600) {
                if (confirm('您的登录会话即将过期，是否继续使用？')) {
                    // 可以在这里发送请求延长会话
                } else {
                    window.location.href = '?logout=1';
                }
            }
        });
    </script>
</body>
</html> 